package com.shuai.robot.xunfei;

import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.shuai.common.constant.ErrorCode;
import com.shuai.common.constant.XfSparkRobotConstant;
import com.shuai.common.exception.BusinessException;
import com.shuai.robot.dto.ChatModelReq;
import com.shuai.robot.utils.OkHttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;

import java.util.Objects;

@Slf4j
public class XunfeiRobotApi {

    /**
     * 以流式输出的方式进行多轮对话
     *
     * @param chatModelReq
     * @param apiKey
     * @param eventSourceListener
     */
    public static void streamSessionReq(ChatModelReq chatModelReq, String apiKey, String apiSecret, EventSourceListener eventSourceListener) {
        if (Objects.isNull(eventSourceListener)) {
            log.error("参数异常：EventSourceListener不能为空");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数异常：EventSourceListener不能为空");
        }

        String auth = apiKey + ":" + apiSecret;
        try {
            EventSource.Factory factory = EventSources.createFactory(OkHttpClientUtil.getClient());
            Request request = new Request.Builder()
                    .url(XfSparkRobotConstant.HOST + XfSparkRobotConstant.URI)
                    .post(RequestBody.create(JSONUtil.toJsonStr(chatModelReq), MediaType.parse(ContentType.JSON.getValue())))
                    .header(XfSparkRobotConstant.AUTHORIZATION_HEADER, "Bearer " + auth)
                    .build();
            // 绑定请求 和 事件监听器
            factory.newEventSource(request, eventSourceListener);
        } catch (Exception e) {
            log.error("请求参数解析异常：{}", e.getMessage());
        }
    }
}
